package com.szxy.miaosha.service.impl;

import com.szxy.miaosha.domain.MiaoshaOrder;
import com.szxy.miaosha.domain.MiaoshaUser;
import com.szxy.miaosha.domain.OrderInfo;
import com.szxy.miaosha.exception.GlobalException;
import com.szxy.miaosha.service.GoodsService;
import com.szxy.miaosha.service.MiaoShaService;
import com.szxy.miaosha.service.MiaoShaUserService;
import com.szxy.miaosha.service.MiaoshaOrderService;
import com.szxy.miaosha.service.OrderInfoService;
import com.szxy.miaosha.utils.CodeMsg;
import com.szxy.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

/**
 * @Author: zwz
 * @Date:2020/9/8 23:33
 * @Description:com.szxy.miaosha.service.impl
 * @Version:1.0
 **/
@Service
public class MiaoShaServiceImpl implements MiaoShaService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MiaoshaOrderService miaoshaOrderService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    @Transactional(rollbackFor = GlobalException.class)
    public void miaoShao(Model model, long goodsId, MiaoshaUser miaoshaUser) {
        // 判断是否有库存
        GoodsVo goodsVo = goodsService.getGoodsByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 0) {
            throw new GlobalException(CodeMsg.STOCK_OVER_ERROR);
        }
        Long userId = miaoshaUser.getId();
        // 判断秒杀过用户是否重复点击秒杀
        MiaoshaOrder miaoshaOrder = miaoshaOrderService.getMiaoShaOrderByUserIdAndGoodsId(userId, goodsId);
        if (miaoshaOrder != null) {
            throw new GlobalException(CodeMsg.REPEACT_CLICK_ERROR);
        }
        // 减库存 下订单 返回订单详情
        goodsService.reduceStock(goodsId);
        OrderInfo orderInfo = orderInfoService.insertOrder(goodsVo, userId);
        // 返回订单详情
        miaoshaOrderService.insertOrder(goodsVo, userId, orderInfo.getId());
        model.addAttribute("goods", goodsVo);
        model.addAttribute("orderInfo", orderInfo);
    }


}
